package com.javacv.plus.extensions.video.steps;

import com.javacv.plus.core.processor.ProcessorContext;
import com.javacv.plus.core.processor.ProcessorStep;
import com.javacv.plus.extensions.video.VideoProcessor;
import com.javacv.plus.extensions.video.VideoResult;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.FFmpegFrameGrabber;

/**
 * 视频加载步骤
 */
@Slf4j
public class LoadVideoStep implements ProcessorStep<VideoProcessor, VideoResult> {

    @Override
    public VideoResult execute(VideoProcessor processor, ProcessorContext context) throws Exception {
        String inputPath = processor.getConfig().getInputPath();
        log.info("正在加载视频: {}", inputPath);

        try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputPath)) {
            grabber.start();

            // 获取视频信息
            VideoResult.VideoInfo videoInfo = new VideoResult.VideoInfo();
            videoInfo.setWidth(grabber.getImageWidth());
            videoInfo.setHeight(grabber.getImageHeight());
            videoInfo.setFrameRate(grabber.getFrameRate());
            videoInfo.setDuration(grabber.getLengthInTime() / 1000000.0); // 转换为秒
            videoInfo.setFormat(grabber.getFormat());

            // 存储到上下文
            context.setAttribute("grabber", grabber);
            context.setAttribute("videoInfo", videoInfo);

            log.info("视频加载成功 - 分辨率: {}x{}, 帧率: {}, 时长: {:.2f}秒",
                    videoInfo.getWidth(), videoInfo.getHeight(),
                    videoInfo.getFrameRate(), videoInfo.getDuration());

        } catch (Exception e) {
            log.error("视频加载失败: {}", e.getMessage());
            throw e;
        }

        return null; // 中间步骤不返回结果
    }

    @Override
    public String getStepName() {
        return "LoadVideo";
    }

    @Override
    public int getPriority() {
        return 10; // 最高优先级，最先执行
    }
} 